package stone.ast;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import runner.Environment;

import java.util.List;

import static runner.Environment.FALSE;

public class IfStmt extends ASTList {
  public IfStmt(List<ASTree> list) {
    super(list);
  }

  @Override
  public String toString() {
    return "(if " + condition() + " " + thenBlock() + " else" + elseBlock() + ")";
  }

  @Nullable
  public ASTree elseBlock() {
    return numChildren() > 2 ? child(2) : null;
  }

  public ASTree thenBlock() {
    return child(1);
  }

  public ASTree condition() {
    return child(0);
  }

  @NotNull
  @Override
  public Object eval(Environment env) {
    Object c = condition().eval(env);
    if (c instanceof Integer && (Integer) c != FALSE)
      return thenBlock().eval(env);
    else {
      ASTree b = elseBlock();
      if (b == null)
        return 0;
      else
        return b.eval(env);
    }
  }
}
